﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.MasterPage;
using Microsoft.SharePoint;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using ProjectFileUrls = Kiiro.Common.Utility.Constants.ProjectFileUrls;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class EditUser : BasePage
    {
        #region Properties
        public new User User
        {
            get
            {
                User user = new User ( );

                if ( ViewState [ "User" ] != null )
                {
                    user = ( User ) ViewState [ "User" ];
                }
                else
                {
                    User = user;
                }

                return user;
            }
            set
            {
                ViewState [ "User" ] = value;
            }
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachments; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );
            CustomFields.ControlMode = SPControlMode.Edit;
            Buttons.SaveButton.ControlMode = SPControlMode.Edit;
            Buttons.CancelButton.ControlMode = SPControlMode.Edit;
            NavigationSub.DeleteButton.ControlMode = SPControlMode.Edit;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            Attachments.MaxLength = 1;
            Attachments.FileFormat = "jpg|png";

            User = UserModel.GetOrCreateUser ( ItemId, SiteCollectionId, ServerRelativeUrl );
            ItemId = User.Id;

            CustomFields.EntityType = typeof ( User );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( User ), ItemId, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.Edit;

            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            NavigationSub.DeleteButton.ItemContext = context;
            NavigationSub.DeleteButton.RenderContext = context;

            litTitle.Text = "Edit User";
            PageTitle = User.FullName;

            if ( !IsPostBack )
            {
                if ( User != null && ( User.UserId == CurrentUser.UserId || CurrentUser.IsAdministrator ) )
                {
                    PopulateForm ( );

                    bool smtpServerExists = SetupModel.GetSMTPServerExists ( SiteCollectionId, ServerRelativeUrl );

                    pnlEmailNotifications.Visible = smtpServerExists;
                    chkReceiveEmail.Checked = smtpServerExists && User.ReceiveEmailNotification;

                    AddCommandButtons ( );
                }
                else
                {
                    Response.Redirect ( String.Format ( "{0}/default.aspx", ServerRelativeUrl ) );
                }
            }
        }
        #endregion

        #region Button Events
        protected void btnChangePassword_Click ( object sender, EventArgs e )
        {
            pnlFormsUser.Visible = false;
            pnlChangePassword.Visible = true;
        }
        #endregion

        #region Methods
        internal override bool Save ( )
        {
            if ( User.UserId == CurrentUser.UserId || CurrentUser.IsAdministrator )
            {
                User.ClearValidationMessages ( );

                User.AddToAllProjects = chkAddToAllProjects.Checked;
                User.CreatedBy = CurrentUser;
                User.CreatedDate = DateTime.Now;
                User.Email = txtEmail.Text;
                User.FirstName = txtFirstName.Text;
                User.IsAdministrator = ckIsAdministrator.Checked;
                User.IsNonExplicitMember = false;
                User.ManageProjectsOnly = !ckIsAdministrator.Checked && ckManageProjects.Checked;
                User.IM = txtIM.Text;
                User.IMClient = txtIMClient.Text;
                User.LastName = txtLastName.Text;

                User.PhoneNumber = txtPhoneNumber.Text;
                if ( pnlChangePassword.Visible )
                {
                    if ( CurrentUser.IsAdministrator )
                    {
                        User.Password = txtNewPassword.Text;
                    }
                    else
                    {
                        if ( !string.IsNullOrEmpty ( txtPassword.Text ) && !string.IsNullOrEmpty ( txtNewPassword.Text ) && !string.IsNullOrEmpty ( txtConfirmPassword.Text ) )
                        {
                            if ( !UserModel.ConfirmCurrentPassword ( User.Login, txtPassword.Text ) )
                                User.PasswordMessage.Add ( new ValidationMessage ( ValidationSeverity.Validation, "Current password is not correct." ) );
                            else if ( txtNewPassword.Text != txtConfirmPassword.Text )
                                User.PasswordMessage.Add ( new ValidationMessage ( ValidationSeverity.Validation, "New password confirmation does not match." ) );
                            else
                                User.Password = txtNewPassword.Text;
                        }
                    }
                }

                User.ReceiveEmailNotification = chkReceiveEmail.Checked;
                User.ServerRelativeUrl = ServerRelativeUrl;
                User.SiteCollectionId = SiteCollectionId;
                User.StatusNote = txtStatusNote.Text;
                User.Title = txtTitle.Text;
                User.ModifiedBy = CurrentUser;
                User.ModifiedDate = DateTime.Now;
                User.CompanyName = txtCompanyName.Text;

                User.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                List<Attachment> attachments = Attachments.GetAttachments ( );
                if ( attachments.Count > 0 )
                {
                    Attachment attachment = attachments.Find ( x => x.Bytes != null && x.EditType != EditType.Deleted );
                    if ( attachment != null )
                    {
                        User.PictureBytes = attachment.Bytes;
                        User.PictureUrl = attachment.FileName;
                    }
                    else
                    {
                        User.PictureUrl = null;
                    }
                }

                User.EditType = EditType.Updated;

                UserModel.Save ( User, SiteCollectionId, ServerRelativeUrl );

                if ( User.IsValid ( ) )
                    Response.Redirect ( Cancel ( ) );
                else
                    LoadErrorMessages ( );
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
            return true;
        }

        internal override string Cancel ( )
        {
            string url = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.UserDisplay, User.SPUserId );

            // to prevent a regular user from being sent to the active projects/summary page check if they can update themselves
            if ( PermissionBitsUsers [ 0 ] || ( !CanUserUpdateThemselves && PermissionBitsUsers [ 2 ] ) || PermissionBitsUsers [ 3 ] )
            {
                if ( SPHelpers.IsPortal ( SiteCollectionId, ServerRelativeUrl ) )
                    url = String.Format ( "{0}{1}", ServerRelativeUrl, PortalFileUrls.UserAll );
                else
                    url = String.Format ( "{0}{1}", ServerRelativeUrl, ProjectFileUrls.Team );
            }

            return url;
        }

        internal override void Delete ( )
        {
            if ( PermissionBitsUsers [ 3 ] )
            {
                User toDelete = User;
                toDelete.ModifiedBy = CurrentUser;
                toDelete.EditType = EditType.Deleted;

                UserModel.Save ( toDelete, SiteCollectionId, ServerRelativeUrl );

                if ( toDelete.IsValid ( ) )
                    Response.Redirect ( Cancel ( ) );
                else
                {
                    KiiroMaster.V2ErrorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( toDelete.EditTypeMessage ) );
                }
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsUsers [ 3 ] && User.Id != CurrentUser.Id )
            {
                LinkButton btnDelete = new LinkButton ( );
                btnDelete.Text = "Delete this User";
                btnDelete.Attributes.Add ( "class", "icon-delete" );
                string js = "javascript:{0}__doPostBack('ctl00$MainContent$V2NavigationSub$diidIODeleteItem','')";
                btnDelete.OnClientClick = string.Format ( js, "if (confirm('Are you sure that you want to delete this user?'))" );
                NavigationSub.Commands.Add ( btnDelete );
            }
        }

        private void PopulateForm ( )
        {
            litTitle.Text = litTitle.Text + " - " + User.FullName;

            bool self = CurrentUser.Id == User.Id;

            if ( self )
            {
                //show first person
                lblMyLogin.Visible = true;
                lblMyPassword.Visible = true;
                lblMyFirstName.Visible = true;
                lblMyLastName.Visible = true;
                lblMyPhoneNumber.Visible = true;
                lblMyTitle.Visible = true;
                lblMyEmailAddress.Visible = true;
                lblMyIMAddress.Visible = true;
                lblMyIMClient.Visible = true;
                lblMyPicture.Visible = true;
                lblMyCompanyName.Visible = true;
                //show status row
                pnlStatus.Visible = true;
                //hide third person
                lblUserLogin.Visible = false;
                lblUserPassword.Visible = false;
                lblUserFirstName.Visible = false;
                lblUserLastName.Visible = false;
                lblUserPhoneNumber.Visible = false;
                lblUserTitle.Visible = false;
                lblUserEmailAddress.Visible = false;
                lblUserIMAddress.Visible = false;
                lblUserIMClient.Visible = false;
                lblUserPicture.Visible = false;
                lblUserCompanyName.Visible = false;

            }

            if ( CurrentUser.IsAdministrator || self )
            {
                if ( CurrentUser.IsAdministrator )
                {
                    pnlAllProjects.Visible = true;
                    pnlIsAdministrator.Visible = !self;
                    pnlCanManageProjects.Visible = !self;
                    currentPasswordRow.Visible = false;
                    confirmPasswordRow.Visible = false;
                }
                else
                {
                    pnlAllProjects.Visible = CurrentUser.ManageProjectsOnly;
                    pnlIsAdministrator.Visible = false;
                    pnlCanManageProjects.Visible = false;
                }

                pnlFormsUser.Visible = User.IsFormsUser;
                txtLogin.Text = User.Login;
                chkAddToAllProjects.Checked = User.AddToAllProjects;
                ckIsAdministrator.Checked = User.IsAdministrator;
                ckManageProjects.Checked = User.IsAdministrator ? User.IsAdministrator : User.ManageProjectsOnly;
                chkReceiveEmail.Checked = User.ReceiveEmailNotification;
                txtEmail.Text = User.Email;
                txtIM.Text = User.IM;
                txtIMClient.Text = User.IMClient;
                txtFirstName.Text = User.FirstName;
                txtLastName.Text = User.LastName;
                txtTitle.Text = User.Title;
                txtPhoneNumber.Text = User.PhoneNumber;
                txtStatusNote.Text = User.StatusNote;
                txtCompanyName.Text = User.CompanyName;

                if ( !string.IsNullOrEmpty ( User.PictureUrl ) )
                {
                    Attachment attachment = new Attachment ( );
                    attachment.FileName = User.PictureUrl.Substring ( User.PictureUrl.LastIndexOf ( "/" ) + 1 );
                    attachment.ServerRelativeUrl = User.PictureUrl;
                    Attachments.SetAttachments ( new List<Attachment> ( ) { attachment } );
                }
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
        }

        private void LoadErrorMessages ( )
        {
            ErrorsList errorsList = ( ( KiiroMaster ) Master ).V2ErrorsList;
            errorsList.ErrorMessages.Add ( "There are some submission errors with the form. Errors will be shown in red below the fields." );

            lblPhoneNumberMessage.Text = FormattingHelpers.GetErrorMessageText ( User.PhoneNumberMessage );
            lblPhoneNumberMessage.Visible = !string.IsNullOrEmpty ( lblPhoneNumberMessage.Text );

            lblTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( User.TitleMessage );
            lblTitleMessage.Visible = !string.IsNullOrEmpty ( lblTitleMessage.Text );

            lblStatusNoteMessage.Text = FormattingHelpers.GetErrorMessageText ( User.StatusNoteMessage );
            lblStatusNoteMessage.Visible = !string.IsNullOrEmpty ( lblStatusNoteMessage.Text );

            lblEmailMessage.Text = FormattingHelpers.GetErrorMessageText ( User.EmailMessage );
            lblEmailMessage.Visible = !string.IsNullOrEmpty ( lblEmailMessage.Text );

            lblIMMessage.Text = FormattingHelpers.GetErrorMessageText ( User.IMMessage );
            lblIMMessage.Visible = !string.IsNullOrEmpty ( lblIMMessage.Text );

            lblIMClientMessage.Text = FormattingHelpers.GetErrorMessageText ( User.IMClientMessage );
            lblIMClientMessage.Visible = !string.IsNullOrEmpty ( lblIMClientMessage.Text );

            lblLastNameMessage.Text = FormattingHelpers.GetErrorMessageText ( User.LastNameMessage );
            lblLastNameMessage.Visible = !string.IsNullOrEmpty ( lblLastNameMessage.Text );

            lblFirstNameMessage.Text = FormattingHelpers.GetErrorMessageText ( User.FirstNameMessage );
            lblFirstNameMessage.Visible = !string.IsNullOrEmpty ( lblFirstNameMessage.Text );

            lblLoginMessage.Text = FormattingHelpers.GetErrorMessageText ( User.LoginMessage );
            lblLoginMessage.Visible = !string.IsNullOrEmpty ( lblLoginMessage.Text );

            string passwordError = FormattingHelpers.GetErrorMessageText ( User.PasswordMessage );
            if ( passwordError.Contains ( "New" ) )
            {
                lblNewPasswordMessage.Text = FormattingHelpers.GetErrorMessageText ( User.PasswordMessage );
                lblNewPasswordMessage.Visible = !string.IsNullOrEmpty ( lblNewPasswordMessage.Text );
            }
            else
            {
                lblPasswordMessage.Text = FormattingHelpers.GetErrorMessageText ( User.PasswordMessage );
                lblPasswordMessage.Visible = !string.IsNullOrEmpty ( lblPasswordMessage.Text );
            }

            lblIsAdministratorMessage.Text = FormattingHelpers.GetErrorMessageText ( User.IsAdministratorMessage );
            lblIsAdministratorMessage.Visible = !string.IsNullOrEmpty ( lblIsAdministratorMessage.Text );

            lblCompanyNameMessage.Text = FormattingHelpers.GetErrorMessageText ( User.CompanyNameMessage );
            lblCompanyNameMessage.Visible = !string.IsNullOrEmpty ( lblCompanyNameMessage.Text );

            lblReceiveEmailMessage.Text = FormattingHelpers.GetErrorMessageText ( User.ReceiveEmailNotificationMessage );
            lblReceiveEmailMessage.Visible = !string.IsNullOrEmpty ( lblReceiveEmailMessage.Text );

            lblAddToAllProjectsMessage.Text = FormattingHelpers.GetErrorMessageText ( User.AddToAllProjectsMessage );
            lblAddToAllProjectsMessage.Visible = !string.IsNullOrEmpty ( lblAddToAllProjectsMessage.Text );

            if ( User.EditTypeMessage.Count > 0 )
            {
                errorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( User.EditTypeMessage ) );
            }
        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.User/User/EditUser.aspx.cs $
 * 
 * 39    2/08/10 5:04p Camerons
 * 
 * 38    2/08/10 2:28p Camerons
 * 
 * 37    1/25/10 1:17p Camerons
 * 
 * 36    1/12/10 12:03p Camerons
 * 
 * 35    1/11/10 11:51a Camerons
 * 
 * 34    1/07/10 12:28p Camerons
 * 
 * 33    1/06/10 12:39p Camerons
 * 
 * 32    12/23/09 3:31p Stefanf
 * 
 * 31    26/11/09 10:35a Camerons
 * 
 * 30    17/11/09 6:46p Camerons
 * 
 * 29    31/10/09 2:59p Camerons
 * 
 * 28    27/10/09 5:39p Camerons
 * Remove IsActive
 * 
 * 27    27/10/09 5:35p Camerons
 * Remove IsActive from forms
 * 
 * 26    10/26/09 2:14p Adamw
 * 
 * 25    16/10/09 5:41p Shafia
 * Set Attachments Properties MaxLength, and FileFormat to allow one file
 * and .jpg or .png files only.
 * 
 * 24    1/10/09 3:28p Camerons
 * Load Expanded ADGroups into drop down on NewTeamMember. Create user on
 * demand if selected user doesn't exist.
 * 
 * 23    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 22    30/09/09 2:03p Camerons
 * 
 * 21    30/09/09 1:08p Camerons
 * Implementing UserModel.GetOrCreateUser(). 
 * 
 * 20    28/09/09 3:38p Camerons
 * 
 * 19    23/09/09 4:46p Camerons
 * Fixed some old code dealing with User.ManageProjects
 * 
 * 18    21/09/09 3:30p Camerons
 * First batch of changes for 1.1.x.x - Security groups update
 * 
 * 17    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/